package com.hk.webapp.controller.client;

import com.hk.webapp.annotations.AllowAnonymous;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

@RestController
public class DownloadController extends ClientBaseController {

    @GetMapping("/download/index")
    @AllowAnonymous
    public void Index(String path, HttpServletRequest request, HttpServletResponse response){
        URL httpUrl;
        BufferedInputStream fis;
        try {
            httpUrl = new URL(path);
            fis = new BufferedInputStream(httpUrl.openStream());
            byte[] buffer = new byte[1024];
            int len =0;
            try {
                //读取消息头 判断浏览器类型
                String fileName=path.substring(path.lastIndexOf('/')+1);
                response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
                response.setHeader( "Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));
                ServletOutputStream outputStream = response.getOutputStream();
                while ((len=fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            } finally {
                fis.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
